var ns;
app = new Vue({
    el: '#app',
    data: {
        showsearch: false,
        showsearchmonth: false,
        showsearchparam: false,
        roomlist: [],
        form: {
            startTime: '',
            endTime: '',
            activeDate: 0,
            ProjectIDs: [],
            statusListIDS:[],
            activeDateDesc: '时间',
        },
        projectList: [],
        summary: {
            AllNumber:'',
            CloseNumber:'',
            ClosePercent:'',
            PersonalNumber:'',
            PublicNumber:''
        },
        activeTransform: '',
        // isOpenJD:false,
        menuitem_selected:0,
        statusList:[
            {"ID":"4","Name":"待受理"},
            {"ID":"5","Name":"待派单"},
            {"ID":"10","Name":"待接单"},
            {"ID":"0","Name":"处理中"},
            {"ID":"1","Name":"已完工"},
            {"ID":"50","Name":"已关单"},
        ],
    },
    methods: {
        get_data: function() {
            var that = this;
            that.getSearchParams();
            setTimeout(function() {
                that.getAnalysisData();
            }, 1000)
        },
        formatactiveTransform: function() {
            var percent = this.summary.ClosePercent*100;
            if (percent <= 50) {
                this.activeTransform = 'transform:rotate(' + (percent / 100) * 360 + 'deg)';
            } else {
                this.activeTransform = 'transform:rotate(' + ((percent / 100) * 360 - 180) + 'deg)';
            }
        },
        doSelectstatus:function(ID){
            var that = this;
            var index = that.form.statusListIDS.indexOf(ID);
            if (index > -1) {
                that.form.statusListIDS.splice(index, 1);
            } else {
                that.form.statusListIDS.push(ID);
            }
        },
        do_chooseservice:function(ID){
            var that = this;
            that.form.statusListIDS=[];
            that.form.statusListIDS.push(ID);
            that.getAnalysisData();
        },
        doSelectProject: function(ID) {
            var that = this;
            var index = that.form.ProjectIDs.indexOf(ID);
            if (index > -1) {
                that.form.ProjectIDs.splice(index, 1);
            } else {
                that.form.ProjectIDs.push(ID);
            }
        },
        getSearchParams: function() {
            var that = this;
            var options = {};
            options.action = "getanalysissearchparam";
            ns.post(options, function(succeed, data, err) {
                if (succeed) {
                    that.projectList = data.projectList;
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            });
        },

        getAnalysisData: function() {
            var that = this;
            var options = {};
            options.SelectStatus=1;
            options.action = "getstatisticslist";//  getserviceanalysissummary  getstatisticslist
            options.ProjectIDs = JSON.stringify(that.form.ProjectIDs);
            options.ServiceStatus = JSON.stringify(that.form.statusListIDS);
            options.StartTime = that.form.startTime;
            options.EndTime = that.form.endTime;
            ns.post(options, function(succeed, data, err) {  
                if (succeed) {
                    console.log(JSON.stringify(data));
                    that.summary = data.ServiceNumbers;
                    that.roomlist=data.data;
                    if(that.roomlist.length>0){
                        setTimeout(function(){
                            that.loadChart(that.roomlist);
                        }, 300);
                    }
                    that.formatactiveTransform();
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true
            });
        },

        doReset: function(type) {
            var that = this;
            if (type == 2) {
                that.form.startTime = '';
                that.form.endTime = '';
                that.form.activeDate = 0;
                that.form.activeDateDesc='时间';
                                                       
            } else {
                that.form.ProjectIDs = [];
                that.form.statusListIDS=[];
            }

        },
        doSearch: function() {
            var that = this;
            that.doHideSearch();
            that.getAnalysisData();
        },
        doSelectSearchParam: function(type) {
            var that = this;
            if (type == 1) { //筛选
                that.showsearchparam = !that.showsearchparam;
                that.showsearchmonth = false;
            }
            if (type == 2) { //按月
                that.showsearchparam = false;
                that.showsearchmonth = !that.showsearchmonth;
            }
            that.showsearch = that.showsearchparam || that.showsearchmonth;
            if (type == 2 && that.showsearchmonth) {
                setTimeout(function () {
                    that.initPicker();
                }, 100);
            }
        },
        doHideSearch: function() {
            var that = this;
            that.showsearchparam = false;
            that.showsearchmonth = false;
            that.showsearch = false;
        },
        doClickDay: function(dataValue) {
            var that = this;
            that.form.activeDate = dataValue;
            var startDate = '',
                endDate = '';
            if (dataValue == 1) {
                var currentDate = dateRangeUtil.getCurrentDate();
                startDate = dateRangeUtil.getDateString(currentDate);
                endDate = startDate;
                that.form.activeDateDesc = '今日';
            }
            if (dataValue == 2) {
                var currentMonth = dateRangeUtil.getCurrentMonth();
                startDate = dateRangeUtil.getDateString(currentMonth[0]);
                endDate = dateRangeUtil.getDateString(currentMonth[1]);
                that.form.activeDateDesc = '本月';
            }
            if (dataValue == 3) {
                var currentYear = dateRangeUtil.getCurrentYear();
                startDate = dateRangeUtil.getDateString(currentYear[0]);
                endDate = dateRangeUtil.getDateString(currentYear[1]);
                that.form.activeDateDesc = '本年';
            }
            that.form.startTime = startDate;
            that.form.endTime = endDate;
        },

        loadChart: function(list) {
            var chart = Highcharts.chart('container', {
                chart: {
                    spacing : [40, 0 , 40, 0]
                },
                credits: {
                    enabled: false //不显示LOGO, '#77D2A9'
                },
                title: {
                    floating:true,
                    text:'总数'+this.summary.AllNumber+'张',
                },
                navigation: {
                    buttonOptions: {
                        enabled: false
                    }
                },
                tooltip: {
                    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
                },
                legend:{
                    align:'center',
                    // labelFormat: '<span style="{color}">{name} {y}'+" "+this.percentage+"%"+'</span>',
                    itemStyle: { 
                        color: '#3E576F' ,
                        fontWeight:'400',
                        fontSize:'11px',
                    },
                    labelFormatter:function(){
                        return "<span style='font-size: 12px;color:#333'>"+this.name+"</span>"+" <br/>" +this.y+"张(占比"+ Highcharts.numberFormat(this.percentage,1) + "%)"
                    }
                },
                plotOptions: {
                    pie: {
                        allowPointSelect: true,
                        cursor: 'pointer',
                        showInLegend: true,
                        dataLabels: {
                            enabled: false,
                        },
                        point: {
                            events: {
                                mouseOver: function(e) {  // 鼠标滑过时动态更新标题
                                    // 标题更新函数，API 地址：https://api.hcharts.cn/highcharts#Chart.setTitle
                                    chart.setTitle({
                                        text: e.target.name+ '\t'+ e.target.y+'张'
                                    });
                                }
                                //, 
                                // click: function(e) { // 同样的可以在点击事件里处理
                                //     chart.setTitle({
                                //         text: e.point.name+ '\t'+ e.point.y + ' %'
                                //     });
                                // }
                            }
                        },
                    }
                },
                series: [{
                    type: 'pie',
                    innerSize: '80%',
                    name: '占比',
                    data:list,
                }]
            }, function(c) { // 图表初始化完毕后的会掉函数
                // 环形图圆心
                var centerY = c.series[0].center[1],
                    titleHeight = parseInt(c.title.styles.fontSize);
                // 动态设置标题位置
                c.setTitle({
                    y:centerY + titleHeight/2
                });
            });
            // var chart = new Highcharts.Chart({
            //     chart: {
            //         renderTo: 'container',
            //         spacing: [40, 0, 40, 0],
            //         panning: false,
            //     },
            //     colors: ['#73c0de','#fac858', '#0E69B3',
			// 	 '#ee6666', '#91cc75', '#FF9655', '#FFF263', '#9B88ED' ,'#289fff'],
            //     credits: {
            //         enabled: false //不显示LOGO, '#77D2A9'
            //     },
            //     navigation: {
            //         buttonOptions: {
            //             enabled: false
            //         }
            //     },

            //     subtitle: {
            //         text: '',
            //     },
            //     tooltip: {
            //         pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
            //     },
            //     legend:{
            //         align:'center',
            //         labelFormat: '<span style="{color}">{name} {y}</span>',
            //         itemStyle: { 
            //            color: '#3E576F' ,
            //            fontWeight:'400',
            //            fontSize:'12px',
            //         }
            //     },
            //     plotOptions: {
            //         pie: {
            //             allowPointSelect: true,
            //             cursor: 'pointer',
            //             dataLabels: {
            //                 enabled: false,
            //             },
            //             showInLegend: true
            //         }
            //     },
                
            //     series: [{
            //         type: 'pie',
            //         colorByPoint:true,
            //         innerSize: '70%',
            //         name: '占比',
            //         data: list,
                    
            //     }]
            // }, function(c) {
                
            // });
        },
        do_select_time: function(type) {
            var that = this;
            var currentTime = type == 1 ? that.form.startTime : that.form.endTime;
            api.openPicker({
                type: 'date',
                date: currentTime,
                title: '选择日期'
            }, function(ret, err) {
                if (ret) {
                    var year = ret.year;
                    var month = (ret.month >= 10 ? ret.month : '0' + ret.month);
                    var day = (ret.day >= 10 ? ret.day : '0' + ret.day);
                    currentTime = year + '-' + month + '-' + day;
                    if (type == 1) {
                        that.form.startTime = currentTime;
                    } else {
                        that.form.endTime = currentTime;
                    }
                }
            });
        },
        do_open_gongdan:function(item,type){
            var that = this;
            ns.openWin('home_task_con_frm', '任务详情', {
                id: item.ID,
                type:type,
                isviewdetail: that.form.isviewdetail
            });

        },

        initPicker: function () {
            var _this = this;
            (function ($, doc) {
                $.init();
                $.ready(function () {
                    //开始日期
                    var btn = document.querySelector('#startdate');
                    btn.addEventListener('tap', function () {
                        var _self = this;
                        if (_self.picker) {
                            _self.picker.show(function (rs) {
                                _this.form.startTime = rs.value;
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        } else {
                            var optionsJson = this.getAttribute('data-options') || '{}';
                            var options = JSON.parse(optionsJson);
                            var id = this.getAttribute('id');
                            _self.picker = new $.DtPicker(options);
                            _self.picker.show(function (rs) {
                                var timer = setTimeout(function () {
                                    clearTimeout(timer);
                                    _this.form.startTime = rs.value;
                                }, 300);
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        }
                    }, false);
                    //结束日期
                    var btnEnd = document.querySelector('#enddate');
                    btnEnd.addEventListener('tap', function () {
                        var _self = this;
                        if (_self.picker) {
                            _self.picker.show(function (rs) {
                                _this.form.endTime = rs.value;
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        } else {
                            var optionsJson = this.getAttribute('data-options') || '{}';
                            var options = JSON.parse(optionsJson);
                            var id = this.getAttribute('id');
                            _self.picker = new $.DtPicker(options);
                            _self.picker.show(function (rs) {
                                var timer = setTimeout(function () {
                                    clearTimeout(timer);
                                    _this.form.endTime = rs.value;
                                }, 300);
                                _self.picker.dispose();
                                _self.picker = null;
                            });
                        }
                    }, false);
                });
            })(mui, document);
        },

    }
});
apiready = function() {
    api.parseTapmode();
    ns = window.Foresight.Util;
    app.doClickDay(1);
    setTimeout(function() {
        app.get_data();
    }, 500)
};
